<template>
  <div class="resume-processing-container">
    <el-config-provider :locale="zhCn">
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button type="primary" @click="add">
            <el-icon><Plus /></el-icon>
            添加
          </el-button>

          <el-dropdown trigger="click">
            <el-button>
              导出<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item 
                  v-for="item in exportOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value">
                  {{ item.label }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <el-dropdown trigger="click">
            <el-button>
              删除<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item 
                  v-for="item in deleteOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value"
                  @click="handleDeleteOption(item)">
                  {{ item.label }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <div class="toolbar-right">
          <el-input 
            class="search-input" 
            placeholder="搜索数据"
            v-model="searchKeyword" 
            @keyup.enter="handleSearch">
            <template #prefix>
              <el-icon class="el-input__icon">
                <search />
              </el-icon>
            </template>
          </el-input>

          <el-button @click="dialog = true">
            <el-icon><Filter /></el-icon>
            筛选
          </el-button>

          <el-button @click="Sorting">
            <el-icon><Sort /></el-icon>
            {{ toggleSort === 1 ? '升序' : '降序' }}
          </el-button>

          <el-button @click="refresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <!-- 卡片容器包装器，用于滚动 -->
      <div class="card-container-wrapper">
        <!-- 卡片 -->
        <div class="card-container">
          <el-card 
            class="box-card" 
            shadow="hover" 
            :key="item.id" 
            v-for="item in page.records" 
            @mouseover.stop="handleMouse(item,true)" 
            @mouseout.stop="handleMouse(item,false)"
            @dblclick="handleCellDblClick(item)">
            <template #header>
              <div class="card-header">
                <el-checkbox 
                  v-model="item.checked" 
                  :class="item.visbleChecked?'visible-checkbox':'card-checkbox'" 
                  @change="handleCheckboxChange(item)">
                </el-checkbox>
                <span class="candidate-id">{{ item.candidateid }}_{{ item.intendedPosition }}</span>
                <el-dropdown placement="bottom-start">
                  <div class="card-actions">
                    <el-button link>
                      <el-icon><MoreFilled /></el-icon>
                    </el-button>
                  </div>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="handleView(item)">查看</el-dropdown-item>
                      <el-dropdown-item @click="handleDelete(item)">
                        <el-text type="danger">删除</el-text>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
            
            <div class="card-content-wrapper">
              <div class="card-row">
                <el-text class="card-label">姓名:</el-text>
                <div class="card-content">
                  <el-icon><User /></el-icon>
                  {{ item.candidatename }}
                </div>
              </div>

              <div class="card-row">
                <el-text class="card-label">学校:</el-text>
                <div class="card-content">{{ item.school }}</div>
              </div>

              <div class="card-row">
                <el-text class="card-label">学历:</el-text>
                <div class="card-content">
                  <template v-if="item.degree === 0">
                    <span>高中</span>
                  </template>
                  <template v-else-if="item.degree === 1">
                    <span>本科</span>
                  </template>
                  <template v-else-if="item.degree === 2">
                    <span>大专</span>
                  </template>
                  <template v-else-if="item.degree === 3">
                    <span>研究生</span>
                  </template>
                  <template v-else>
                    <span>其他</span>
                  </template>
                </div>
              </div>

              <div class="card-row">
                <el-text class="card-label">专业:</el-text>
                <div class="card-content">{{ item.specialized }}</div>
              </div>

              <div class="card-row">
                <el-text class="card-label">加入日期:</el-text>
                <div class="card-content">{{ item.dateofresumeaddition }}</div>
              </div>

              <div class="card-footer">
                <template v-if="item.resumeStatus === '待面试'">
                  <el-tag type="primary">{{ item.resumeStatus }}</el-tag>
                </template>
                <template v-else-if="item.resumeStatus === '已入职'">
                  <el-tag type="success">{{ item.resumeStatus }}</el-tag>
                </template>
                <template v-else-if="item.resumeStatus === '已淘汰'">
                  <el-tag type="danger">{{ item.resumeStatus }}</el-tag>
                </template>
                <template v-else>
                  <el-tag type="info">{{ item.resumeStatus }}</el-tag>
                </template>
              </div>
            </div>
          </el-card>
        </div>
      </div>
      
      <div class="pagination-container">
        <el-pagination 
          @current-change="cardList" 
          v-model:current-page="page.current" 
          v-model:page-size="page.size"
          :page-sizes="[10, 20, 30, 40]" 
          layout="total, sizes, prev, pager, next, jumper" 
          :total="page.total">
        </el-pagination>
      </div>
    </el-config-provider>
  </div>
  
  <el-dialog :title="DetailsId + '_' + intendedPosition" fullscreen destroy-on-close v-model="ResumeDetailsShow">
    <hr>
    <Details :date="DetailsId"></Details>
  </el-dialog>
  
  <el-dialog title="添加简历" fullscreen destroy-on-close v-model="ResumeAdditionDisplay">
    <hr>
    <insert></insert>
  </el-dialog>
  
  <!--筛选  -->
  <el-drawer v-model="dialog" title="筛选" direction="rtl" class="demo-drawer">
    <div class="demo-drawer__content">
      <el-form :model="form" style="height: 600px;">
        <el-select 
          v-model="Screening" 
          placeholder="筛选" 
          style="width: 100%" 
          placement="bottom">
          <template #label="{ label, value }">
            <span style="font-weight: bold">{{ label }}</span>
          </template>
          <el-option 
            v-for="item in FilterData" 
            :key="item.value" 
            :label="item.label" 
            :value="item.value" />
        </el-select>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" :loading="loading" @click="onClick">
          {{ loading ? '提交中 ...' : '提交' }}
        </el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import request from '@/api/request'
import { ref } from 'vue'
import Details from './Details.vue'
import insert from './insert.vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Filter, Sort, Refresh, MoreFilled, User } from '@element-plus/icons-vue'

const dialog = ref(false); //抽屉
const loading = ref(false) //加载
const ResumeDetailsShow = ref(false)//简历详情显示
const ResumeAdditionDisplay = ref(false)//简历添加显示
const searchKeyword = ref('') // 搜索关键词
const Screening = ref(null) //筛选
const FilterData = ref([ //筛选数据
  { value: '全部', label: '全部' },
  { value: '待面试', label: '待面试' },
  { value: '已淘汰', label: '已淘汰' },
  { value: '已入职', label: '已入职' },
])

let page = ref({ // 分页数据 
  current: 1, // 当前页
  size: 10, // 每页条数
  total: 0, // 总条数
  records: [] // 数据
})

let toggleSort = ref(1) // 排序
let isChecked = ref(false) // 全选
const savedData = ref([])
const DetailsId = ref(null); // 详情id
const intendedPosition = ref(null);//岗位

//导出下拉框
const exportOptions = ref([
  { label: '全部', value: '' },
  { label: '待处理', value: '待处理' },
  { label: '处理中', value: '处理中' },
  { label: '处理完成', value: '处理完成' },
  { label: '处理失败', value: '处理失败' },
])

//删除下拉框
const deleteOptions = ref([
  { label: '删除全部数据', value: '删除全部数据' },
  { label: '删除已选数据', value: '删除已选数据' },
])

// 监听选中项变化并输出到控制台
const handleCheckboxChange = (item) => {
  // 检查 item 是否已存在于 savedData 中
  const index = savedData.value.findIndex(data => data.candidateid === item.candidateid)
  
  if (item.checked) {
    // 如果复选框被选中且数据不存在于数组中，则添加
    if (index === -1) {
      savedData.value.push(item)
    }
  } else {
    // 如果复选框未被选中且数据存在于数组中，则移除
    if (index !== -1) {
      savedData.value.splice(index, 1)
    }
  }
  
  console.log('选中项发生变化:', savedData.value)

  // 获取所有选中的项
  //const selectedItems = page.value.records.filter(record => record.checked);
  //console.log('当前所有选中项:', selectedItems);
  isChecked.value = page.value.records.some(record => record.checked) // 判断是否有选中项
  page.value.records.forEach(item => { // 遍历每一行
    item.visbleChecked = isChecked.value // 设置每一行的可见性
  })
}

// 排序
const Sorting = () => {
  toggleSort.value = toggleSort.value === 1 ? 2 : 1 //如果排序状态为1，则切换为2，否则切换为1
  const url =
    toggleSort.value === 1 // 如果排序状态为1 
      ? '/candidateresume/sortByDate'
      : '/candidateresume/sortByDateDesc'

  request({
    url,
    method: 'get',
    params: {
      pageNum: page.value.current,
      pageSize: page.value.size,
      searchKeyword: searchKeyword.value,
      intendedPosition: searchKeyword.value,// 添加搜索关键词参数
      resumeStatus: Screening.value // 添加筛选参数
    }
  }).then(res => {
    page.value = res.data
  })
}

// 获取数据
const cardList = () => {
  request({
    url: '/candidateresume/findByStatus',
    method: 'post',
    params: {
      current: page.value.current, // 当前页
      size: page.value.size, // 每页条数
      total: page.value.total,
      intendedPosition: searchKeyword.value,// 添加搜索关键词参数
      resumeStatus: Screening.value // 筛选状态
    }
  }).then(res => {
    page.value = res.data // 更新分页数据
    ElMessage.success('已获取' + page.value.total + '条数据')
    console.log(res);
  }).catch(error => {
    console.error('获取数据失败:', error)
  })
}

// 处理搜索
const handleSearch = () => {
  // 重置到第一页并重新加载数据
  page.value.current = 1
  cardList()
}

cardList()

const refresh = () => {
  toggleSort.value = 1;
  Screening.value = null;
  cardList()
}

const add = () => {
  ResumeAdditionDisplay.value = true
}

const handleCellDblClick = (item) => {
  ElMessage.success('双击了单元格')
  ResumeDetailsShow.value = true;
  DetailsId.value = item.candidateid
  intendedPosition.value = item.intendedPosition
  console.log(item);
}

// 处理查看操作
const handleView = (item) => {
  ResumeDetailsShow.value = true;
  DetailsId.value = item.candidateid
  intendedPosition.value = item.intendedPosition
  console.log(item);
}

// 处理删除操作
const handleDelete = (item) => {
  console.log('删除简历:', item)
  // 这里可以添加删除确认对话框和实际删除逻辑
  ElMessageBox.confirm(
    `你确定要删除"${item.candidateid}"吗?`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error',
    }
  ).then(() => {
    request({
      url: '/candidateresume/deleteById',
      method: 'post',
      params: {
        candidateid: item.candidateid
      }
    }).then(response => {
      console.log('删除成功:', response);
      ElMessage.success('删除成功');
      // 重新加载数据
      cardList();
    }).catch(error => {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
      // 重新加载数据
      cardList();
    });
  }).catch(() => {
    // 用户点击取消
    ElMessage.info('已取消操作');
  });
}

// 删除选项处理
const handleDeleteOption = (option) => {
  if (option.value === '删除全部数据') {
    ElMessageBox.confirm(
      '你确定要删除全部数据吗?',
      '通知',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error',
      }
    ).then(() => {
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    }).catch(() => {
      ElMessage({
        type: 'warning',
        message: '取消操作',
      })
    })
  } else if (option.value === '删除已选数据') {
    if (savedData.value.length === 0) {
      ElMessage.warning('请先选择要删除的数据');
      return;
    }
    
    ElMessageBox.confirm(
      `你确定要删除选中的${savedData.value.length}条数据吗?`,
      '通知',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error',
      }
    ).then(() => {
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      // 实际删除逻辑应在这里实现
    }).catch(() => {
      ElMessage({
        type: 'warning',
        message: '取消操作',
      })
    })
  }
}

const form = ref();

const onClick = () => {//筛选提交
  loading.value = true
  if (Screening.value) {
    request({
      url: '/candidateresume/findByStatus',
      method: 'post',
      params: {
        intendedPosition: searchKeyword.value, // 添加搜索关键词参数
        resumeStatus: Screening.value
      }
    }).then(res => {
      page.value = res.data
      ElMessage.success('已为你找到' + page.value.total + '条数据')
      setTimeout(() => {
        dialog.value = false
      }, 400)
    })
  } else {
    ElMessage.error('你还未选择')
  }
  loading.value = false
  return;
}

//取消
const cancelForm = () => {
  loading.value = false
  dialog.value = false
}

const handleMouse = (item,flag) => { //鼠标移入移出
  if(isChecked.value){  // 如果已选中任何项，则不处理鼠标悬停
    return; 
  }
  item.visbleChecked = flag 
}
</script>

<style scoped>
.resume-processing-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 100px);
  padding: 20px;
  background-color: #f5f7fa;
  overflow: hidden;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 16px 20px;
  margin-bottom: 20px;
  flex-shrink: 0;
}

.toolbar-left {
  display: flex;
  gap: 12px;
}

.toolbar-right {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-input {
  width: 200px;
}

.card-container-wrapper {
  flex: 1;
  overflow: hidden;
  margin-bottom: 20px;
}

.card-container {
  display: grid;
  grid-template-columns: repeat(5, minmax(0, 1fr));
  gap: 20px;
  padding: 10px;
  height: 100%;
  overflow: auto;
}

.box-card {
  border-radius: 8px;
  transition: all 0.3s ease;
  cursor: pointer;
  background-color: #fff;
  border: 1px solid #ebeef5;
}

.box-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.candidate-id {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
  flex: 1;
  text-align: center;
}

.card-content-wrapper {
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 20px;
}

.card-row {
  display: flex;
  align-items: flex-start;
}

.card-label {
  width: 80px;
  font-weight: 500;
  color: #909399;
  font-size: 13px;
  flex-shrink: 0;
  line-height: 1.5;
}

.card-content {
  flex: 1;
  font-size: 14px;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 6px;
  line-height: 1.5;
}

.card-footer {
  margin-top: 10px;
  display: flex;
  justify-content: center;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.card-checkbox,
.card-actions {
  opacity: 0;
  transition: opacity 0.3s ease;
}

.visible-checkbox {
  opacity: 1;
}

.box-card:hover .card-actions {
  opacity: 1;
}

.pagination-container {
  flex-shrink: 0;
  display: flex;
  justify-content: flex-end;
  padding: 20px 0;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 16px 20px;
}

.demo-drawer__content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.demo-drawer__content .el-form {
  flex: 1;
}

.demo-drawer__footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
}

/* 响应式设计 - 当屏幕较小时调整每行卡片数量 */
@media (max-width: 1600px) {
  .card-container {
    grid-template-columns: repeat(4, minmax(0, 1fr));
  }
}

@media (max-width: 1300px) {
  .card-container {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }
}

@media (max-width: 992px) {
  .card-container {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .toolbar-left,
  .toolbar-right {
    width: 100%;
    flex-wrap: wrap;
  }
  
  .search-input {
    width: 100%;
  }
  
  .card-container {
    grid-template-columns: repeat(1, minmax(0, 1fr));
  }
  
  .card-header {
    padding: 12px 15px;
  }
  
  .card-content-wrapper {
    padding: 15px;
    gap: 12px;
  }
  
  .card-label {
    width: 70px;
    font-size: 12px;
  }
  
  .card-content {
    font-size: 13px;
  }
}
</style>